#include "../proto/database.pb.h"
#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h>
#include <string>
#include <iostream>

using namespace google::protobuf;

void determineFieldTypes(const Descriptor*, int);
void determineNestedFields(const Descriptor*);

string getDataFromSocket(string& data, Message* database)
{
/*	try
    {
      // Create the socket
      ServerSocket server ( 30000 );
	  ServerSocket new_sock;
	  server.accept ( new_sock );
  

	  try
	    {
		  new_sock >> data;
		  new_sock << "Received Successfully!";

	    }
	  catch ( SocketException& ) {}

    }
  catch ( SocketException& e )
    {
      std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
    }

	
	database->ParseFromString(data);
	
	database->PrintDebugString();
	*/ 
	return data;
}

int main ( int argc, char* argv[] )
{
  cout << "Listening for a connection....\n";
  string data;
  string ack = "Message Received";
  
  Message* database = new db::Database;
  const Descriptor* msgDescript = database->GetDescriptor();
  
  determineFieldTypes(msgDescript, msgDescript->field_count());  
  
  determineNestedFields(msgDescript);
	


  const Reflection* dataInfo = database->GetReflection();	  
	
	//Function in progress
	//getDataFromFields(dataInfo);



	
  return 0;
}



void determineFieldTypes(const Descriptor* msgDescript, int maxFieldCnt)
{
	for(int fieldCnt = 0; fieldCnt < maxFieldCnt; fieldCnt++)
	{
		const FieldDescriptor* msgField = msgDescript->field(fieldCnt);
		

		if(msgField->type()==FieldDescriptor::TYPE_BOOL)
		{
			cout<<msgField->name()<<" is a Boolean."<<endl;
		}
		else if(msgField->type()==FieldDescriptor::TYPE_STRING)
		{
			cout<<msgField->name()<<" is a String."<<endl;
			//getStringFromField
		}
		else if(msgField->type()==FieldDescriptor::TYPE_INT32)
		{
			cout<<msgField->name()<<" is an INT32."<<endl;
		}
		else if(msgField->type()==FieldDescriptor::TYPE_FLOAT)
		{
			cout<<msgField->name()<<" is a Float."<<endl;
		}
		else if(msgField->type()==FieldDescriptor::TYPE_DOUBLE)
		{
			cout<<msgField->name()<<" is a Double."<<endl;
		}						
		else if(msgField->type()==FieldDescriptor::TYPE_MESSAGE)
		{
			cout<<msgField->name()<<" is a nested Message."<<endl;
		}						

	}
}

void determineNestedFields(const Descriptor* msgDescript)
{
	for(int nestedCnt = 0; nestedCnt < msgDescript->nested_type_count(); nestedCnt++)
	{
		const Descriptor* nestedMsg = msgDescript->nested_type(nestedCnt);
		
		cout<<"Nested message "<<nestedMsg->name()<<" has the following fields: "<<"\n";
		
		determineFieldTypes(nestedMsg, nestedMsg->field_count());	
		
		
	}	
}
